<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="sku信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- Tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
           <el-form-item label="商品名称" prop="spuName">
              <el-input v-model="addForm.spuName"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="spuDescription">
              <el-input v-model="addForm.spuDescription"></el-input>
            </el-form-item>
            <!-- <el-form-item label="商品价格" prop="price">
              <el-input v-model="addForm.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <el-input v-model="addForm.weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="number">
              <el-input v-model="addForm.number" type="number"></el-input>
            </el-form-item> -->
            <el-form-item label="商品分类" prop="catId">
              <el-cascader
               ref="cascader"
                v-model="addForm.catId"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="选择品牌" prop="brandId">
              <el-select v-model="addForm.brandId" placeholder="请选择">
                <el-option
                  v-for="(item,i) in brands"
                  :key="i"
                  :label="item.brandName"
                  :value="item.brandId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
           <el-tab-pane label="商品属性" name="1">
            <el-form-item :label="item.attrName" v-for="item in onlyTableData" :key="item.attrId">
              <el-input v-model="item.valueSelect"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="2">
            <!-- 渲染表单的Item项 -->
            <el-form-item
              v-for="item in attrs"
              :key="item.attrId"
              :label="item.attrName"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.valueSelect">
                <el-checkbox :label="cb" v-for="(cb, i) in item.valueSelect" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="sku信息" name="3">
            <el-table
              :data="addForm.skus"
              style="width: 100%" border="">
               <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column
                property="skuName"
                label="商品名称"
                width="280">
              </el-table-column>
              <el-table-column
                property="tockCount"
                label="商品库存"
                width="100">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.tockCount">{{scope.row.tockCount}}</el-input>
                </template>
              </el-table-column>
              <el-table-column
                property="weight"
                label="商品重量(kg)"
                width="150">
                 <template slot-scope="scope">
                  <el-input v-model="scope.row.weight">{{scope.row.weight}}</el-input>
                </template>
              </el-table-column>
              <el-table-column
                property="price"
                label="价格(元)"
                width="150">
                 <template slot-scope="scope">
                  <el-input v-model="scope.row.price">{{scope.row.price}}</el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="4">
            <el-form-item label="商品图集" prop="images">
              <OssUploads v-model="images"></OssUploads>
            </el-form-item>
             <el-form-item label="商品介绍" prop="decript">
              <OssUploads v-model="decript"></OssUploads>
            </el-form-item>
            <!-- 添加商品 -->
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
            
          </el-tab-pane>
          <!-- <el-tab-pane label="商品内容" name="4"> -->
            <!-- 富文本编辑器 -->
            <!-- <quill-editor v-model="addForm.goods_introduce"></quill-editor> -->
            <!-- 添加商品 -->
            <!-- <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button> -->
          <!-- </el-tab-pane> -->
        </el-tabs>
      </el-form>
    </el-card>
    <!-- <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="picPreviewPath" alt="" class="previewImg">
    </el-dialog> -->
  </div>
</template>

<script>
import _ from 'lodash'
import OssUploads from '../upload/OssUploads.vue'
export default {
  data () {
    return {
      // 步骤条默认激活 与左侧Tab联动
      activeIndex: '0',
      // 添加商品的表单对象
      addForm: {
        spuName:"",
        spuDescription:"",
        brandId:'',
        catalogId:'',
        // 商品所属分类数组
        images:[],
        // 商品详情描述
        decript:[],
        // 规格参数数据
        onlyTableData:[],
        skus:[],
        // spuName: '',
        // price: 0,
        // weight: 0,
        // number: 0,
        // // 商品所属分类数组
        // catId: [],
        // // 图片的数组
        // pics: [],
        // // 商品详情描述
        // goods_introduce: '',
        // attrs: []
      },
      addFormRules: {
        spuName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        catId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品参数
      attrs:[],
       skuData:{
       attrs:[],
       skuName: "",
       price: '',
       skuTitle: "",
       descar: "",
       weight: "",
       tockCount: ''
      },
      decript:[],
      images:[],
      // 商品列表
      cateList: [],
      // 级联选择器配置
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'catName',
        value: 'catId',
        children: 'children'
      },
      // 品牌选择器数据
      brands:[],
      // 动态参数列表数据
      // manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      
      // picPreviewPath: '',
      // 图片预览对话框
      // previewDialogVisible: false
    }
  },
  components:{
    OssUploads
  },
  created () {
    this.getCateList()
  },
  // 监听属性值的改变，进而改变sku商品名
  watch:{
    attrs: {
      handler(newName, oldName) {
        const goodsName=[]
        newName.forEach(item =>{
          goodsName.push(item.attrValue)  
        })
        // console.log(newName)
        this.skuData.skuName =  this.addForm.proName + ' ' + goodsName.join(" ")
      // console.log(this.skuData.skuName)
    },
    deep: true,
    immediate: true
    },
    images: {
      handler(newName, oldName) {
        const goodsImages=[]
        newName.forEach(item =>{
          goodsImages.push(item.url)  
        })
        this.addForm.images =  goodsImages
      // console.log(this.addForm.images)
    },
    deep: true,
    immediate: true
    },
    decript: {
      handler(newName, oldName) {
        const goodsDecript=[]
        newName.forEach(item =>{
          goodsDecript.push(item.url)  
        })
        this.addForm.decript =  goodsDecript
      // console.log(this.addForm.decript)
    },
    deep: true,
    immediate: true
    }
  },
  computed: {
    getCateId () {
      if (this.addForm.catalogId.length === 2) {
        return this.addForm.catalogId[1]
      }
      return null
    }
  },
  methods: {
    // 获取分类
    async  getCateList(){
        const {data:res} = await this.$http.get("/xuanmall/category/list/tree")
        if(res.code === 0){
         this.cateList = this.formatData(res.data)
        }
      },
     // 格式化数据，递归将空的children置为undefined
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatData(data[i].children)
        }
      }
      return data
      },
      // 获取所有品牌
    async  getBrands(){
      const {data:res} = await this.$http.get(`/xuanmall/categorybrandrelation/brands/list?catId=${this.addForm.catalogId}`)
      console.log(res)
      this.brands = res.data
    },
    // 级联选择器选中项变化时触发
    handleChange () {
      this.brands = []
      var nodeInfo = this.$refs.cascader.getCheckedNodes()
      // console.log(nodeInfo)
      this.addForm.catalogId = nodeInfo[0].data.catId;
      this.getBrands()
    },
    beforeTabLeave (activeName, odlActiveName) {
      // 未选中商品分类阻止Tab标签跳转
      if (odlActiveName === '0' && this.addForm.catalogId === '') {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // Tab标签被选中时触发
    async tabClicked () {
      // 访问动态参数面板
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`xuanmall/attr/sale/list/${this.getCateId}`)
        if (res.code !== 0) {
          return this.$message.error('获取商品参数列表失败！')
        }
        this.attrs=[]
          res.page.list.forEach(item1 => {
            item1.valueSelect = item1.valueSelect ? item1.valueSelect.split('，') : []
            const data={}
            data.attrId = item1.attrId,
            data.attrName = item1.attrName,
            data.attrValue = '',
            data.valueSelect = item1.valueSelect
            this.attrs.push(data)
          }) ;
        // res.data.forEach(item => {
        //   item.valueSelect =
        //     item.valueSelect.length === 0 ? [] : item.valueSelect.split(' ')
        // })
        // this.manyTableData = res.data
      } else if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`/xuanmall/attrgroup/${this.getCateId}/withattr`)
        if (res.code !== 0) {
          return this.$message.error('获取商品属性列表失败！')
        }
        this.addForm.onlyTableData = res.data
        // res.data.forEach(item => {
        //   item.attrs.forEach(item1 => {
        //     item1.valueSelect = item1.valueSelect ? item1.valueSelect.split('，') : []
        //     const data={}
        //     data.attrId = item1.attrId,
        //     data.attrName = item1.attrName,
        //     data.valueSelect = item1.valueSelect
        //     this.addForm.onlyTableData.push(data)
        //   })  
        // });
        // this.onlyTableData = res.data
      }
    },
    // 处理图片预览
    // handlePreview (file) {
    //   this.picPreviewPath = file.response.data.url
    //   this.previewDialogVisible = true
    // },
    // 处理移除图片的操作
    // handleRemove (file) {
    //   // 1.获取将要删除图片的临时路径
    //   const filePath = file.response.data.tmp_path
    //   // 2.从pics数组中，找到图片对应的索引值
    //   const i = this.addForm.pics.findIndex(x => x.pic === filePath)
    //   // 3.调用splice方法，移除图片信息
    //   this.addForm.splice(i, 1)
    // },
    // 监听图片上传成功事件
    // handleSuccess (response) {
    //   // 1.拼接得到一个图片信息对象 临时路径
    //   const picInfo = { pic: response.data.tmp_path }
    //   // 2.将图片信息对象，push到pics数组中
    //   this.addForm.pics.push(picInfo)
    // },
    // sku信息保存
    addGoodsInfo(){
      this.skuData.attrs = this.attrs
      this.addForm.skus.push(this.skuData)
      this.$message.success("保存成功")
      this.skuData = {
      attrs:[],
       price: '',
       skuTitle: "",
       descar: "",
       weight: "",
       tockCount: ''}
    },
    // 删除sku
    handleDelete(row){
      // console.log(row)
      var index = 0
       index = this.addForm.skus.map(item =>{
        if(item.skuName === row.skuName) {
          return index
        }
        index = index + 1
      })
      this.addForm.skus.splice(index,1)
    },
    // 添加商品
    addGoods () {
      
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
        // 发送请求前：需对提交的表单进行处理goods_cat attrs
        // this.addForm.catId = this.addForm.catId.join(',')
        // 以上写法不对：级联选择器绑定的对象goods_cat要求是数组对象
        // 解决办法: 包：lodash 方法（深拷贝）：cloneDeep(boj)

        // 将this.addForm进行深拷贝
        const form = _.cloneDeep(this.addForm)
        form.catId = form.catId.join(',')

        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attrId: item.attrId,
            attr_value: item.valueSelect.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attrId: item.attrId,
            attr_value: item.valueSelect
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // 发起请求添加商品
        // 商品名称必须是唯一的
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功!')
        this.$router.push('/goodsadd')
      })
    }
  }
}
</script>

<style lang='less' scoped>
.el-checkbox {
  margin: 0 8px 0 0 !important;
}
.previewImg{
  width: 100%;
}
.btnAdd{
  margin-top: 15px
}
</style>
